import { login, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    portrait: '',
    perms: []
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, portrait) => {
    state.portrait = portrait
  },
  SET_PERMS: (state, perms) => {
    state.perms = perms
  }
}

const actions = {
    // 登录
    login({ commit }, userInfo) {
        const { username, password } = userInfo
        return new Promise((resolve, reject) => {
            login({ username: username.trim(), password: password }).then(response => {
                // debugger
                let  data  = response
                commit('SET_TOKEN', data.access)
                // setToken(data.access)
                // sessionStorage.setItem('user_id',data.userInfo.user_id)
                // sessionStorage.setItem('userData', JSON.stringify(data.userInfo))
                localStorage.clear()
                localStorage.setItem('userToken', JSON.stringify(data.access))
                // commit('setUserData', data.userInfo)
                // 设置登录状态为false
                // commit('setIsLogin', true)
                resolve()
            }).catch(error => {
                reject(error)
            })
        })
    },

    // 获取用户信息
    // getInfo({ commit, state }) {
    //     console.log(state)
    //     return new Promise((resolve, reject) => {
    //         debugger
    //         if (!sessionStorage.getItem('userData')) {
    //             reject('验证失败，请重新登录')
    //         }
    //         const userInfo = JSON.parse(sessionStorage.getItem('userData'))
    //         if(!userInfo.roles) {
    //             console.error('权限不能为空数组，否则路由死循环')
    //             return
    //         }
    //         // userInfo.roles = ['admin']
    //         commit('setRoles', userInfo.roles)
    //         resolve(userInfo)
    //     })
    // },

    getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        let data  = response
        if (!data) {
          reject('验证失败,重新登陆.')
        }
        // debugger
        localStorage.setItem('user_id',data.id)
        const { perms, name, avatar } = data

        // perms must be a non-empty array
        if (!perms || perms.length <= 0) {
          reject('没有任何权限!')
        }

        commit('SET_PERMS', perms)
        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)
        resolve(data)
      }).catch(error => {
          debugger
          // token失效  清除
        reject('token失效，请重新登录!')
        localStorage.removeItem('user_id')
        localStorage.removeItem('userToken')
        reject(error)
      })
    })
  },



    // 退出登录
    logout({ commit, state, dispatch }) {
        return new Promise((resolve, reject) => {
            // commit('setToken', '')
            // 清除用户数据
            commit('setUserData', '')
            // 清楚用户权限集合
            commit('setRoles', [])
            // 设置登录状态为false
            commit('setIsLogin', false)
            // 清除缓存的用户数据
            localStorage.removeItem('user_id')
            localStorage.removeItem('userToken')
            // 清除缓存的多页签数据
            dispatch('tagsView/setRouterArr', [], { root: true })
            localStorage.removeItem('dataRouter')
            resolve()
        })
    },

    resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }

    // // 设置用户数据
    // setUserData(context, data) {
    //     context.commit('setUserData', data);
    // },
    // // 修改登陆状态
    // setIsLogin(context, data) {
    //     context.commit('setIsLogin', data);
    // }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}
